package com.fingard.dsp.bank.directbank.zjrb01;

import org.apache.commons.lang.StringUtils;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by F on 2018/4/26.
 */
public class ZJRB01SinglePay extends ZJRB01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try{
            String opName = "BSpaySubmitOp";
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommenHeader(xmlTextWriter,opName);
            XElement RepParam = new XElement("ReqParam","");
            RepParam.addChild(new XElement("Pay_Dep_name",p_req1908.singleDetail.payName));//汇付单位
            RepParam.addChild(new XElement("Pay_Dep_Acc",p_req1908.singleDetail.payAct));//汇付帐号
            RepParam.addChild(new XElement("Area_code",p_req1908.singleDetail.payArea));//区域代码，暂时不清楚选什么字段
            RepParam.addChild(new XElement("Pay_Dep_branch",p_req1908.singleDetail.payBankLocation));//汇款单位开户行
            RepParam.addChild(new XElement("Rec_Dep_name",p_req1908.singleDetail.recName));//收款单位
            RepParam.addChild(new XElement("Rec_Dep_Acc",p_req1908.singleDetail.recAct));//收款账号
            RepParam.addChild(new XElement("Rec_Area_Code",p_req1908.singleDetail.sameBnk));//是否同行，1同行，0同行
            RepParam.addChild(new XElement("Rec_Dep_branch",p_req1908.singleDetail.recBankLocation));//收款方开户行
            RepParam.addChild(new XElement("Trans_time", Format.DateTimeFormat.format(p_req1908.singleDetail.getPayDateTime())));//交易时间
            RepParam.addChild(new XElement("Serial_no",p_req1908.singleDetail.askNumber));//指令序号
            RepParam.addChild(new XElement("PayAmt",converYuanToFen(p_req1908.singleDetail.payAmount)));//金额，以分为单位
            RepParam.addChild(new XElement("Account_cur",convertCurToBank(p_req1908.singleDetail.payCur)));//币种
            RepParam.addChild(new XElement("Pay_Use",p_req1908.singleDetail.purpose));//用途
            RepParam.addChild(new XElement("Pay_type",p_req1908.singleDetail.paySpd));//是否加急
            RepParam.addChild(new XElement("Submit_Log_id",p_req1908.singleDetail.submitID));//提交人
            RepParam.addChild(new XElement("Area_name",p_req1908.singleDetail.payAreaName));//付款人账户地区名(付款人所在地)
            RepParam.addChild(new XElement("Rec_Area_name",p_req1908.singleDetail.recAreaName));//收款人账户地区名
            RepParam.addChild(new XElement("Branch_code",""));//账户分理处号
            RepParam.addChild(new XElement("Pay_Password",""));//支付密码
            RepParam.addChild(new XElement("User_Rem",p_req1908.singleDetail.memo));//摘要
            RepParam.addChild(new XElement("Pay_NetCode",""));//付款行网点号
            RepParam.addChild(new XElement("Pay_BranchNo",""));//付款行行号
            RepParam.addChild(new XElement("Pay_BranchId",""));//付款行行标识
            RepParam.addChild(new XElement("Pay_DispsNo",""));//付款行分签号
            RepParam.addChild(new XElement("Rec_BranchNo",""));//对方行号
            RepParam.addChild(new XElement("Rec_BranchId",""));//对方行标识
            RepParam.addChild(new XElement("Rec_DispsNo",""));//对方分签号
            RepParam.addChild(new XElement("PostScript",p_req1908.singleDetail.purpose));//附言
            RepParam.addChild(new XElement("Transfer_Type",""));//转帐类型
            RepParam.addChild(new XElement("userID",bankFront.loginName));//企业代码（和证书里的一致）
            String packageID = p_req1908.singleDetail.askNumber;
            RepParam.addChild(new XElement("PackageID",packageID.length()>14?packageID.substring(0,15): StringUtils.repeat("0",15-packageID.length())+packageID));//包序列ID（15位）
            RepParam.addChild(new XElement("ReqReserved1",""));//请求包备用字段1
            RepParam.addChild(new XElement("ReqReserved2",""));//请求包备用字段2

            nodeAnalysis(p_req1908.singleDetail.srcXElement,RepParam,getCharset());

            wirteReqBody(xmlTextWriter,RepParam,null);
            xmlTextWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
            if(bankResult[0].length()==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1],tmpSbMsg);
                if(tmpBkReader!=null){
                    String retCode = tmpBkReader.getFirstText("/ROOT/opRep/opResult/retCode");
                    if("0".equals(retCode)){
                        detail.respCode = "0";
                        detail.respInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                        detail.reqSeqID = p_req1908.reqHeader.reqSeqID;
                        detail.transState = retCode;
                        detail.payInfoCode= retCode;
                    }else{
                        detail.respCode = "-1";
                        detail.respInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                    }
                }else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            }else if (bankResult[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = bankResult[0];
            }else{
                detail.respCode="-1";
                detail.respInfo = bankResult[1];
            }
        }catch (Exception ex){
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try{
            String opName = "BSQueryPayOrderOp";
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommenHeader(xmlTextWriter,opName);
            XElement ReqParam = new XElement("ReqParam","");
            ReqParam.addChild(new XElement("userID",bankFront.loginName));
            String packageID = p_req1944.askNumber;
            ReqParam.addChild(new XElement("PackageID",packageID.length()>14?packageID.substring(1,15):StringUtils.repeat("0",15-packageID.length())+packageID));
            ReqParam.addChild(new XElement("ReqReserved1",""));
            ReqParam.addChild(new XElement("ReqReserved2",""));
            wirteReqBody(xmlTextWriter,ReqParam,null);
            xmlTextWriter.writeEndDocument();
            String [] bankResult = sendToBank(xmlTextWriter.toXmlString());
            if(bankResult[0].length()==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1],tmpSbMsg);
                if(tmpBkReader!=null){
                    String retCode = tmpBkReader.getFirstText("/ROOT/opRep/opResult/retCode");
                    if("0".equals(retCode)){
                        detail.respCode = "0";
                        detail.respInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                        detail.reqSeqID = tmpBkReader.getFirstText("/ROOT/opRep/opResult/PackageID");
                        detail.transState ="0+"+tmpBkReader.getFirstText("/ROOT/opRep/opResult/Result");
                        detail.payInfoCode = detail.transState;
                    }else if("1".equals(retCode)){
                        detail.respCode = "-1";
                        detail.respInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                    }else{
                        detail.respCode = "0";
                        detail.respInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                        detail.reqSeqID = tmpBkReader.getFirstText("/ROOT/opRep/opResult/PackageID");
                        detail.transState =retCode;
                        detail.payInfoCode = detail.transState;
                    }
                }else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            }else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }
        }catch (Exception ex){
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAtsSingle.writeRetDetail(detail);
        return retAtsSingle;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
